package com.bins.mongodb.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.bins.mongodb.dao.UserMongoDbDao;
import com.bins.mongodb.entity.UserEntity;

@Service
public class UserService {
    
    @Autowired
    private UserMongoDbDao userMongoDbDao;
    
    public String saveUser(UserEntity user) {
    	user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
    	userMongoDbDao.save(user);
        return "添加成功";
    }

    public List<UserEntity> findAll() {
        return userMongoDbDao.findAll(UserEntity.class);
    }

    public UserEntity getUserById(Long id) {
        return userMongoDbDao.queryById(id);
    }

    public String updateUser(UserEntity user) {
        Query query = new Query(Criteria.where("_id").is(user.getId()));
        Update update = new Update()
        		.set("userName", user.getUserName())
                .set("age", user.getAge())
                .set("updateTime", new Date());
        userMongoDbDao.updateFirst(query, update, UserEntity.class);
        return "success";
    }

    public String deleteUser(UserEntity user) {
    	userMongoDbDao.delete(user);
        return "success";
    }

    public String deleteUserById(Long id) {
    	userMongoDbDao.deleteById(id);
        return "success";
    }
}